package cn.liukuan.jps.utils;

import javassist.*;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.store.RedisSerializableClient;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by liukuan on 16/5/30.
 */
public class JavassistUtils {

    public static void addInterface(String target, String interfaceName) throws NotFoundException, CannotCompileException {

        ClassPool pool = ClassPool.getDefault();

        CtClass ctClass = pool.getCtClass(target);

        ctClass.addInterface(pool.get(interfaceName));

        CtField serialVersionUID = new CtField(CtClass.longType, "serialVersionUID", ctClass);

        serialVersionUID.setModifiers(Modifier.PRIVATE);

        ctClass.addField(serialVersionUID, "0l");

        ctClass.toClass();

    }

    public static void replaceFlatMap(String target, String source) throws NotFoundException, CannotCompileException, NoSuchFieldException, IllegalAccessException, IOException {

        ClassPool pool = ClassPool.getDefault();

        CtClass ctClass = pool.getCtClass(target);

        CtClass[] type = {pool.get("org.apache.lucene.store.LockFactory")};

        CtConstructor constructor = ctClass.getDeclaredConstructor(type);

        System.out.println(constructor.getLongName());

//        CtConstructor[] constructors = ctClass.getConstructors();
//
//        for (CtConstructor constructor : constructors) {
//
//            System.out.println(constructor.getName() + "   " + constructor.getLongName());
//        }

        constructor.insertAfter("{this.fileMap=cn.liukuan.jps.utils.RedisUtils.getRedisClient();}");

        ctClass.toClass();
//        ctClass.writeFile();
    }


//    public static Integer getRunPort() throws Exception {
//
//        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
//
//        List<String> inputArguments = runtimeMXBean.getInputArguments();
//
//        for (String inputArgument : inputArguments) {
//
//            if(inputArgument.contains("address=")){
//                String[] split = inputArgument.split(",");
//                for (String s : split) {
//                    if(s.startsWith("address=")){
//                        String[] hostport = s.split(":");
//                        return Integer.parseInt(hostport[1]);
//                    }
//                }
//            }
//
//        }
//
//        throw new Exception();
//    }

}
